﻿/* =====================================================
 *  Copyright (C) by Huu Tai Analyzer.
 *  Encrypt string value.
 * ===================================================== */
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

/// <summary>
/// Describe the algorithm:
/// - Encrypt with the available algorithm of CSharp.
// - Encrypt is built by the manual algorithm.
/// </summary>
class Encrypt
{
    #region Members Of Class
    static string bangA = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    static string bangB = "2R5MsdYOu9SoJ4exLtwfXK0bIP" + "TnUcQjikVhW16vrqGHBZyz3DEml7CaApN8Fg";
    #endregion

    #region Show/Hide password fixed length is 60.
    public static string Hide(string pwd)
    {
        return pwd.PadRight(60, '#');
    }

    public static string Show(string pwd)
    {
        return pwd.Replace("#", "");
    }
    #endregion

    #region Encrypt algorithm.
    public static string Encode(string algorithm, string password)
    {
        // Tạo HashAlgorithm của kiểu được qui định bởi
        // đối số dòng lệnh thứ nhất.
        using (HashAlgorithm hashAlg = HashAlgorithm.Create(algorithm))
        {
            // Chuyển chuỗi password (đối số dòng lệnh thứ hai)
            // thành một mảng byte.
            byte[] pwordData = Encoding.Default.GetBytes(password);

            // Tạo mã băm của password.
            byte[] hash = hashAlg.ComputeHash(pwordData);

            return BitConverter.ToString(hash);
        }
    }
    #endregion

    #region Encrypt password.
    public static string Encode(string pwd)
    {
        string kq = string.Empty;

        if (!CheckPass(pwd, bangA))
            return null;

        foreach (char kt in pwd)
            kq += bangB.Substring(Mid(bangA, kt), 1);

        return kq;
    }

    /* Decrypt password */
    public static string Decode(string pwd)
    {
        string bangA = "abcdefghijklmnopqrstuvwxyz";
        bangA += "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        string bangB = "2R5MsdYOu9SoJ4exLtwfXK0bIP";
        bangB += "TnUcQjikVhW16vrqGHBZyz3DEml7CaApN8Fg";

        string kq = "";

        foreach (char kt in pwd)
            kq += bangA.Substring(Mid(bangB, kt), 1);

        return kq;
    }

    #region Support to Encrypt method.
    private static bool CheckPass(string pwd, string bangA)
    {
        foreach (char kt in pwd)
            if (!bangA.Contains(kt.ToString()))
                return false;
        return true;
    }

    private static int Mid(string str, char kt)
    {
        int c = 0;
        foreach (char k in str)
        {
            if (kt == k) return c;
            c++;
        }
        return c;
    }
    #endregion
    #endregion
}